import React, { forwardRef, useEffect, useState } from 'react'
import { 
  Input,
  Form,
  Select
} from 'antd';
const { Option } = Select;

const UserForm = forwardRef((props, ref) =>  {
  const [isDisabled, setIsDisabled] = useState(false)
  const {roleId} = JSON.parse(localStorage.getItem('token'))

  useEffect(() => {
    setIsDisabled(props.updateFlag)
  }, [props.updateFlag])
  
  
  // form表单实例
  const [form] = Form.useForm()

  const roleChange = (value) => {
    console.log(value)
    if(Number(value) === 1) {
      setIsDisabled(true)
      ref.current.setFieldsValue({
        region: ''
      })
    } else {
      setIsDisabled(false)
    }
  }

  const checkRegionDisabled = (item) => {
      if (props.updateFlag === 0) {
        // 新建
        if(roleId === 1) {
          return false
        } else {
          return true
        }
      } else {
        // 编辑
        if(roleId === 1) {
          return false
        } else {
          return true
        }
      }
  }

  return (
    <Form
      ref={ref}
      form={form}
      layout="vertical"
      name="form_in_modal"
      initialValues={{ modifier: 'public' }}
    >
    <Form.Item
      name="userName"
      label="用户名"
      rules={[{ required: true, message: 'Please input the title of collection!' }]}
    >
      <Input />
    </Form.Item>
    <Form.Item 
      name="passwor" 
      label="密码"
      rules={[{ required: true, message: 'Please input the title of collection!' }]}
    >
      <Input type="password" />
    </Form.Item>
    <Form.Item 
      name="region"
      label="区域"
      rules={isDisabled ? [] : [{ required: true, message: 'Please input the title of collection!' }]}
    >
      <Select disabled={isDisabled}>
        {
          props.regoinList.map(item => 
            <Option 
              value={item.id} 
              key={item.id}
              disabled={checkRegionDisabled(item)}
            >{item.regoin}</Option>
          )
        }
      </Select>
    </Form.Item>
    <Form.Item 
      name="roleId"
      label="角色"
    >
      <Select onChange={(val) => roleChange(val)}>
        {
          props.roleList.map(item => 
            <Option 
              value={item.id} 
              key={item.id}
            >{item.role}</Option>
          )
        }
      </Select>
    </Form.Item>
  </Form>
  )
})

export default UserForm
